package cn.yangliu.mybatis.config;


import cn.yangliu.jdbc.config.DataSourceConfig;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 作者 杨柳
 * 创建时间 2017-08-23 00:57
 */
@Configuration // 配置注解
@AutoConfigureAfter(DataSourceConfig.class)
public class MybatisConfig {

   @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(DataSource dataSource, PaginationInterceptor paginationInterceptor, GlobalConfiguration globalConfiguration){
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        org.springframework.core.io.Resource [] resources = null;
        try {
            resources = resourcePatternResolver.getResources("classpath*:mybatis/*.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        bean.setMapperLocations(resources);
        bean.setTypeAliasesPackage("cn.yangliu.entity");
        PaginationInterceptor[] interceptors = {paginationInterceptor};
        bean.setPlugins(interceptors);
        bean.setGlobalConfig(globalConfiguration);
        return bean;
    }

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor interceptor = new PaginationInterceptor();
        interceptor.setLocalPage(true);
        return interceptor;
    }
    @Bean
    public GlobalConfiguration globalConfiguration(){
        GlobalConfiguration configuration = new GlobalConfiguration();
        return configuration;
    }


}
